import java.io.File

import org.apache.commons.lang3.StringUtils
import scopt.OParser

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import Implicits._
import scala.sys.process._


/**
  * Created by yz on 2019/1/23
  */


case class Config(dir: File = new File("marmot_scala_js-1.0"),
                  port: Int = 80
                 )

object Main {


  def main(args: Array[String]): Unit = {

    val builder = OParser.builder[Config]
    val parser1 = {
      import builder._
      //s r h w m e n t o
      OParser.sequence(
        programName("scopt"),
        head("scopt", "4.x"),
        opt[File]('d', "dir").valueName("<file>").action { (x, c) =>
          c.copy(dir = x)
        }.text("please input project dir name!"),
        opt[Int]('p', "port").valueName("<int>").action { (x, c) =>
          c.copy(port = x)
        }.text("please input port number!"),
        help("help").text("prints this usage text")
      )
    }
    OParser.parse(parser1, args, Config()) match {
      case Some(config) => exec(config)
      case _ =>
    }

    def exec(config: Config) = {
      val workDir = new File(".")
      val dir = config.dir
      val dirName = dir.getName
      if (dir.exists()) {
        val pidFile = new File(dir, "RUNNING_PID")
        val pid = pidFile.str
        val command =
          s"""
             |kill -s 9 ${pid}
             |rm -rf ${dir.getName}*
           """.stripMargin
        val execCommand = Utils.callScript(workDir, ArrayBuffer(command))
        execCommand.logStr
      } else {
        val command =
          s"""
             |unzip ${dirName}.zip
             |nohup ./${dirName}/bin/${dirName.replaceAll("-1.0$", "")} -Dhttp.port=${config.port} > ${dirName.split("_")(0)}.out 2>&1 &
           """.stripMargin
        val execCommand = Utils.callScript(workDir, ArrayBuffer(command))
        execCommand.logStr
      }


    }


  }


}
